import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL || '/'),
  routes: [
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/RegistPage.vue')
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/LoginPage.vue')
    },
    {
      path: '/',
      component: () => import('@/components/IndexPage.vue'), // 布局组件
      redirect: '/home',
      children: [
        {
          path: 'home',
          name: 'Home',
          component: () => import('@/views/HomePage.vue'),
          meta: {
            title: '首页',
            requireRole: [0,1,2]
          }
        },
          {
            path: 'user',
            name: 'User',
            component: () => import('@/components/user/UserPage.vue'),
            meta: {
              title: '用户管理',
              requireRole: [0, 1] // 0: 超级管理员, 1: 管理员
            }
          },
        {
          path: 'admin',
          name: 'Admin',
          component: () => import('@/components/admin/AdminPage.vue'),
          meta: {
            title: '管理员管理',
            requireRole: [0]
          }
        },
        {
          path: 'storage',
          name: 'Storage',
          component: () => import('@/components/storage/StoragePage.vue'),
          meta: {
            title: '仓库管理',
            requireRole: [0, 1, 2] // 0: 超级管理员, 1: 管理员
          }
        },
        {
          path: 'goodsType',
          name: 'GoodsType',
          component: () => import('@/components/goodsType/GoodsTypePage.vue'),
          meta: {
            title: '货物分类管理',
            requireRole: [0, 1, 2] // 0: 超级管理员, 1: 管理员
          }
        },
        {
          path: 'goods',
          name: 'Goods',
          component: () => import('@/components/goods/GoodsPage.vue'),
          meta: {
            title: '货物管理',
            requireRole: [0, 1, 2] // 0: 超级管理员, 1: 管理员
          }
        },
        {
          path: 'record',
          name: 'Record',
          component: () => import('@/components/record/RecordPage.vue'),
          meta: {
            title: '记录管理',
            requireRole: [0, 1, 2] // 0: 超级管理员, 1: 管理员
          }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/home'
    }
  ]
})
// 动态生成路由
// const generateRoutesFromMenu = (menus) => {
//   return menus.map(menu => ({
//     path: menu.path,
//     component: () => import(`@/components/${menu.component}.vue`),
//     meta: { title: menu.name }
//   }))
// }

// 监听 Vuex 中的菜单数据
// store.watch(
//     (state) => state.menu,
//     (newMenu) => {
//       const dynamicRoutes = generateRoutesFromMenu(newMenu)
//       dynamicRoutes.forEach(route => router.addRoute(route))
//     }
// )

// 路由守卫
router.beforeEach((to, from, next) => {
  const user = JSON.parse(localStorage.getItem('user'));
  const requireRole = to.meta.requireRole;
  console.log('当前路由:', to.path); // 调试日志
  console.log('用户角色ID:', user?.roleId); // 调试日志
  console.log('所需角色:', requireRole); // 调试日志
  // 1. 处理登录页和注册页的访问
  if (to.path === '/login' || to.path === '/register') {
    user ? next('/home') : next(); // 已登录跳首页，未登录允许访问
    return;
  }

  // 2. 检查是否登录
  if (!user) {
    next('/login');
    return;
  }

  // 3. 检查角色权限
  if (requireRole && !requireRole.includes(user.roleId)) {
    console.log('无权限访问，跳转首页'); // 调试日志
    next('/home'); // 无权限跳首页
    return;
  }

  // 4. 允许访问
  next();
});


export default router
